package org.gtiles.components.login.ext;

import java.util.HashMap;
import java.util.Map;

import org.gtiles.components.login.authentication.IAuthenticateAction;
import org.gtiles.components.login.authentication.IAuthenticatedUser;
import org.gtiles.components.login.authentication.impl.AuthenticatedUserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 用户登录
 * 
 * @author HuGuangJun
 */
public class CustomAuthenticateAction implements IAuthenticateAction {
	private LoginServiceClient client = new LoginServiceClient();
	/**
	 * 获取当前用户，并授权
	 */
	public IAuthenticatedUser doAuthenticate(final String inputLoginID) throws AuthenticationException {
		String loginID = inputLoginID;
		//用户名登录,值为1，FIXME 后续修改为常量		
		LoginAuthBean loginInfo = client.getLoginInfoByLoginID(loginID);
		if (loginInfo != null) {
			if(loginInfo.getAccountState() == 4){
				throw new CredentialsExpiredException("该用户账号已作废：" + loginID);
			}
			else if(loginInfo.getAccountState() == 3){
				throw new LockedException("该用户账号已锁定：" + loginID);
			}
			else if(loginInfo.getAccountState() == 2){
				throw new DisabledException("该用户账号未激活：" + loginID);
			}
			AuthenticatedUserImpl authUser = new AuthenticatedUserImpl(loginInfo.getUserId(), inputLoginID,
					loginInfo.getName(), loginInfo.getPassword());
			authUser.setUserName(loginInfo.getUserName());
			authUser.setNickName(loginInfo.getNickName());
			Map<String, Object> extInfo = new HashMap<String, Object>();
			extInfo.put("headPhoto", loginInfo.getHeadPhoto());
			extInfo.put("accountId", loginInfo.getAccountId());
			authUser.setExtendAccountInfo(extInfo);
			return authUser;
		} else {
			throw new UsernameNotFoundException("用户不存在：" + inputLoginID);
		}
	}
}
